//
//  BFShOrderHomeViewController.m
//  BeautyFood
//
//  Created by apple on 2020/5/5.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "BFShOrderHomeViewController.h"
#import "BFShOrderHeaderView.h"
#import "BFShOrderTableViewCell.h"
#import "BFShOrderFooterView.h"
#import "THLookWuLiuViewController.h"
#import "BFShOrderDetailViewController.h"
#import "THCommentOrderGoodViewController.h"
#import "BFApplyAfterSaleViewController.h"
#import "BFAfterSaleProcessViewController.h"
@interface BFShOrderHomeViewController ()
@property(nonatomic, strong) STTools_SegementAutoView                     *auto_view;/**<  */
@property(nonatomic, strong) NSMutableArray                     *dataSouce;/**<  */

@end

@implementation BFShOrderHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的订单";
    [self stoneobs_ui_configSubView];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.didLoad) {

    }
}
#pragma mark --configSubView
- (void)stoneobs_ui_configSubView{
    __weak typeof(self) weakSelf =  self;
    STTools_SegementAutoView * auto_view = [[STTools_SegementAutoView alloc] initWithFrame:CGRectMake(0, TMUtils.stoneobs_fun_get_navgationBarBootom, STONEOBS_UI_UISCREEN_WIDTH, 45) andTitle:@[@"代付款",@"待发货",@"待收货",@"已完成",@"售后中",@"全部"] handle:^(STTools_SegementAutoView *sender, UIButton *currentSelctedButton) {
        weakSelf.dataSouce = NSMutableArray.new;
        weakSelf.tableView.mj_footer.hidden = YES;
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_header beginRefreshing];
    }];
    auto_view.butTitleColor = STONEOBS_UI_FIRST_TEXT_COLOR;
    auto_view.butTitleSelectedColor = STONEOBS_UI_THEME_BACKGROUNDCOLOR;
    auto_view.lineSelectedColor = STONEOBS_UI_THEME_BACKGROUNDCOLOR;
    auto_view.lineColor = STONEOBS_UI_THEME_BACKGROUNDCOLOR;
    auto_view.lineColor = UIColor.clearColor;
    auto_view.autoMoveWithClic = YES;
    [self.view addSubview:auto_view];
    self.auto_view = auto_view;
    
    self.tableView.frame = CGRectMake(0, self.auto_view.bottom, STONEOBS_UI_UISCREEN_WIDTH, TMUtils.stoneobs_fun_get_tabBarTop+49 - self.auto_view.bottom);
    self.tableView.contentInset = UIEdgeInsetsZero;
    
    [self.tableView registerClass:BFShOrderHeaderView.class forHeaderFooterViewReuseIdentifier:@"BFShOrderHeaderView"];
    [self.tableView registerClass:BFShOrderTableViewCell.class forCellReuseIdentifier:@"BFShOrderTableViewCell"];
    [self.tableView registerClass:BFShOrderFooterView.class forHeaderFooterViewReuseIdentifier:@"BFShOrderFooterView"];
    
    
    self.tableView.st_noreslutView = [[STTools_NoresultView alloc] initWithFrame:CGRectMake(0, self.tableView.tableHeaderView.height + 30, STONEOBS_UI_UISCREEN_WIDTH, 400) title:@"暂无数据" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf stoneobs_send_list_request];
    }];
    
    
    if (self.selcted_index == 0) {
        [self.tableView.mj_header beginRefreshing];
    }else{
        self.auto_view.cureentIndex = self.selcted_index;
        [self.tableView.mj_header beginRefreshing];
    }
}

#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return BFShOrderHeaderView.stoneobs_ui_cell_height;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BFShOrderHeaderView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"BFShOrderHeaderView"];
    BFShOrderModel * model = self.dataSouce[section];
    header.model = model;
    __weak typeof(self) weakSelf =  self;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf tableView:tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
    }];
    [header addGestureRecognizer:tap];
    header.userInteractionEnabled = YES;
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return BFShOrderTableViewCell.stoneobs_ui_cell_height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return BFShOrderFooterView.stoneobs_ui_cell_height;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    BFShOrderFooterView * footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"BFShOrderFooterView"];
    BFShOrderModel * model = self.dataSouce[section];
    footer.model = model;
    __weak typeof(self) weakSelf =  self;
    [footer setDidSlectedMenuTitle:^(NSString * _Nonnull title) {
        [BFShOrderHomeViewController onSelctedMenuTitle:title model:model];
    }];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf tableView:tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
    }];
    [footer addGestureRecognizer:tap];
    footer.userInteractionEnabled = YES;
    return footer;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    BFShOrderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[BFShOrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    BFShOrderModel * model = self.dataSouce[indexPath.section];
    cell.model = model;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BFShOrderModel * model = self.dataSouce[indexPath.section];
    self.selected_model = model;
    BFShOrderDetailViewController * vc = BFShOrderDetailViewController.new;
    vc.o_id = model.o_id;
    [self pushViewController:vc animated:1];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
+ (void)onSelctedMenuTitle:(NSString*)title model:(BFShOrderModel*)model{

    if ([title isEqualToString:@"去支付"]) {
        THZhiFuViewController * vc = THZhiFuViewController.new;
        vc.order_id = model.o_id;
        vc.pay_money = @(model.total_price.floatValue).description;
        [TMUtils.stoneobs_fun_get_currentTopController pushViewController:vc animated:1];

    }
    if ([title isEqualToString:@"取消订单"]) {
        [TMUtils.stoneobs_fun_get_currentTopController stoneobs_fun_st_showAlertTitle:@"确定要取消订单吗？" message:@"" leftTitle:@"不了" rightTitle:@"取消订单" block:^(NSString *name) {
            if ([name isEqualToString:@"取消订单"]) {
                [BFShOrderDataController stoneobs_fun_send_cancle_order:model.o_id handle:^(NSError *error, BOOL success, NSDictionary *resp) {
                    if ([TMUtils.stoneobs_fun_get_currentTopController isKindOfClass:BFShOrderHomeViewController.class]) {
                        BFShOrderHomeViewController * vc = (id)TMUtils.stoneobs_fun_get_currentTopController ;
                        model.status = @"401";
                        [vc.tableView reloadData];
                        [vc.tableView.mj_header beginRefreshing];
                    }
                    if ([TMUtils.stoneobs_fun_get_currentTopController isKindOfClass:BFShOrderDetailViewController.class]) {
                        BFShOrderHomeViewController * vc = (id)TMUtils.stoneobs_fun_get_currentTopController_lastControllerIfNav;
                        vc.selected_model.status = @"401";
                        [vc.tableView reloadData];
                        [vc.tableView.mj_header beginRefreshing];
                        [TMUtils.stoneobs_fun_get_currentTopController.navigationController popViewControllerAnimated:YES];
                    }
                }];
            }
        }];
    }
    if ([title isEqualToString:@"确认收货"]) {
        if (model.status.intValue == 0 ) {
            [TMUtils.stoneobs_fun_get_currentTopController stoneobs_fun_st_showAlertTitle:@"确认收货前需要支付订单哦" message:@"" leftTitle:@"取消" rightTitle:@"支付" block:^(NSString *name) {
                if ([name isEqualToString:@"支付"]) {
                    [self onSelctedMenuTitle:@"去支付" model:model];
                }
            }];
        }else{
            [TMUtils.stoneobs_fun_get_currentTopController stoneobs_fun_st_showAlertTitle:@"确定要确认收货吗？" message:@"" leftTitle:@"取消" rightTitle:@"确认" block:^(NSString *name) {
                if ([name isEqualToString:@"确认"]) {
                    [BFShOrderDataController stoneobs_fun_send_confim_order:model.o_id handle:^(NSError *error, BOOL success, NSDictionary *resp) {
                        
                        model.status = @"3";
                        [TMUtils.shorderHomeControllerIfExit.tableView reloadData];
                        if ([TMUtils.stoneobs_fun_get_currentTopController isKindOfClass:BFShOrderDetailViewController.class]) {
                            BFShOrderHomeViewController * vc = (id)TMUtils.stoneobs_fun_get_currentTopController;
                            [vc.navigationController popViewControllerAnimated:YES];
                        }
                    }];
                }
            }];
        }

    }
    if ([title isEqualToString:@"删除订单"]) {
        [TMUtils.stoneobs_fun_get_currentTopController stoneobs_fun_st_showAlertTitle:@"确定要删除订单吗？" message:@"" leftTitle:@"不了" rightTitle:@"删除订单" block:^(NSString *name) {
            if ([name isEqualToString:@"删除订单"]) {
                [BFShOrderDataController stoneobs_fun_send_delete_order:model.o_id handle:^(NSError *error, BOOL success, NSDictionary *resp) {
                    if ([TMUtils.stoneobs_fun_get_currentTopController isKindOfClass:BFShOrderHomeViewController.class]) {
                        BFShOrderHomeViewController * vc = (id)TMUtils.stoneobs_fun_get_currentTopController ;
                        model.status = @"-2";
                        [vc.tableView reloadData];
                        [vc.tableView.mj_header beginRefreshing];
                    }
                    if ([TMUtils.stoneobs_fun_get_currentTopController isKindOfClass:BFShOrderDetailViewController.class]) {
                        BFShOrderHomeViewController * vc = (id)TMUtils.stoneobs_fun_get_currentTopController_lastControllerIfNav;
                        vc.selected_model.status = @"-2";
                        [vc.tableView reloadData];
                        [vc.tableView.mj_header beginRefreshing];
                        [TMUtils.stoneobs_fun_get_currentTopController.navigationController popViewControllerAnimated:YES];
                    }
                }];
            }
        }];
    }
    if ([title isEqualToString:@"去评价"]) {
        THCommentOrderGoodViewController * vc = THCommentOrderGoodViewController.new;
        vc.oid = model.o_id;
        [TMUtils.stoneobs_fun_get_currentTopController pushViewController:vc animated:1];
        
    }
    if ([title isEqualToString:@"查看物流"]) {
        THLookWuLiuViewController * vc = THLookWuLiuViewController.new;
        vc.oid = model.o_id;
//        vc.oid = @"162";
        [TMUtils.stoneobs_fun_get_currentTopController pushViewController:vc animated:1];
    }

    if ([title isEqualToString:@"申请售后"]) {
        BFApplyAfterSaleViewController * vc = BFApplyAfterSaleViewController.new;
        vc.model = model;
        [TMUtils.stoneobs_fun_get_currentTopController pushViewController:vc animated:1];
    }
    if ([title isEqualToString:@"查看售后"]) {
        BFAfterSaleProcessViewController * vc = BFAfterSaleProcessViewController.new;
        vc.model = model;
        [TMUtils.stoneobs_fun_get_currentTopController pushViewController:vc animated:1];
    }
}
#pragma mark --stoneobs_net netWork Method
- (void)configRefreshFooter{
    __weak typeof(self) weakSelf =  self;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf stoneobs_send_list_request];
    }];
}
- (void)stoneobs_send_list_request{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    if (self.auto_view.cureentIndex > -1 && self.auto_view.cureentIndex < 4) {
        [stoneobs_net_param_dic setObject:@(self.auto_view.cureentIndex) forKey:@"status"];
    }
    if (self.auto_view.cureentIndex == 4) {
        [stoneobs_net_param_dic setObject:@(6) forKey:@"status"];
    }
    [stoneobs_net_param_dic setObject:@(self.page) forKey:@"page"];
    //http://bf.xingzhuosong.com//v1/goods/goodsList?name=%E8%92%9C%E8%8B%97&page=1
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/orders/orders"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumGet
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        CGFloat total = [[responseObject valueForKey:@"data"][@"total"] floatValue];
        CGFloat perPage = [[responseObject valueForKey:@"data"][@"perPage"] floatValue];;//每一页数据
        total = ceil(total/perPage);//总共多少页
        
        NSArray * array = [responseObject valueForKey:@"data"][@"items"];
        NSArray * objArry = [BFShOrderModel mj_objectArrayWithKeyValuesArray:array];
        if (self.page == 1) {
            self.dataSouce = NSMutableArray.new;
            [self.tableView.mj_header endRefreshing];
            if (total > self.page) {
                [self configRefreshFooter];
            }
        }else{
            if (total > self.page) {
                [self.tableView.mj_footer endRefreshing];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        [self.dataSouce addObjectsFromArray:objArry];
        [self.tableView reloadData];
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        if (self.page > 1) {
            self.page --;
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
    
}
@end
